/*
 Copyright [2012] [Aleksey Shipilev]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

package net.shipilev;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Handle;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import static org.objectweb.asm.Opcodes.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * Walks around source code, and intrinsifies INDY calls.
 *
 * @goal indy
 * @phase process-classes
 */
public class IndyMojo extends AbstractMojo {

    private static final String PREFIX = "INDY_trampoline_";

    /**
     * Classes dir
     *
     * @parameter expression="${project.build.directory}"
     * @required
     */
    private File classesDirectory;

    public void execute() throws MojoExecutionException {
        try {
            Files.walkFileTree(classesDirectory.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.toString().endsWith("class")) {
                        process(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new MojoExecutionException("IOException", e);
        }
    }

    private void process(Path p) throws IOException {
        try (
            InputStream input = Files.newInputStream(p)
        ) {
            ClassReader reader = new ClassReader(input);
            ClassWriter writer = new ClassWriter(reader, 0);
            reader.accept(new ClassVisitor(ASM4, writer) {
                @Override
                public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
                    return new IndyTranslator(mv);
                }
            } , 0);
            input.close();
            Files.write(p, writer.toByteArray());
        }
    }

    public class IndyTranslator extends MethodVisitor {

        public IndyTranslator(MethodVisitor mv) {
            super(ASM4, mv);
        }

        @Override
        public void visitMethodInsn(int opcode, String owner, String name, String desc) {
            if (opcode == INVOKESTATIC) {
                if (name.startsWith(PREFIX)) {
                    String bsmName = name.replace(PREFIX, "");

                    getLog().info("Found matching method " + name + " " + desc + ", converting to invokedynamic with " + owner + "::" + bsmName + " as the bootstrap");

                    Handle mh = new Handle(Opcodes.H_INVOKESTATIC, owner, bsmName,
                            MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class).toMethodDescriptorString());

                    super.visitInvokeDynamicInsn(bsmName, desc, mh);
                    return;
                }
            }

            super.visitMethodInsn(opcode, owner, name, desc);
        }
    }

}

